package com.toilet.easyvideofx.view;

import atlantafx.base.controls.RingProgressIndicator;
import atlantafx.base.controls.Tile;
import com.toilet.easyvideofx.compent.RequestComponent;
import com.toilet.easyvideofx.constant.StyleConstant;
import com.toilet.easyvideofx.manager.DownLoadFileService;
import com.toilet.easyvideofx.model.FileListModel;
import javafx.application.Platform;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.value.ChangeListener;
import javafx.collections.ObservableList;
import javafx.concurrent.Worker;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.util.Callback;
import org.kordamp.ikonli.antdesignicons.AntDesignIconsOutlined;
import org.kordamp.ikonli.javafx.FontIcon;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件列表自定义ListView
 */
public class FileListView implements Callback<ListView<FileListModel>, ListCell<FileListModel>> {
    /**
     * 进度条宽度
     */
    private final DoubleBinding width;
    /**
     * 是否开始下载
     */
    private Boolean isStart = Boolean.FALSE;
    /**
     * 文件列表
     */
    private ObservableList<FileListModel> fileObservableList;

    /**
     * 下载的大小
     */
    public FileListView(DoubleBinding width, ObservableList<FileListModel> fileObservableList) {
        this.width = width;
        this.fileObservableList = fileObservableList;
    }

    @Override
    public ListCell<FileListModel> call(ListView<FileListModel> param) {
        return new ListCell<>() {
            @Override
            protected void updateItem(FileListModel item, boolean empty) {
                super.updateItem(item, empty);
                if (!empty) {
                    //展示项
                    BorderPane borderPane = new BorderPane();
                    borderPane.getStylesheets().add("css/controller/main-controller.css");
                    borderPane.getStyleClass().add("list-view-download-vbox-hbox");

                    HBox hBox = new HBox();
                    hBox.setAlignment(Pos.CENTER_LEFT);
                    ImageView view = new ImageView("image/video.ico");
                    view.setPreserveRatio(true);
                    view.setFitHeight(30);
                    Tile tile = new Tile(item.getFileName(), item.getFileMd5());

                    Button download = new Button(null, new FontIcon(AntDesignIconsOutlined.DOWNLOAD));
                    Button delete = new Button(null, new FontIcon(AntDesignIconsOutlined.DELETE));
                    delete.setOnMouseClicked(event -> Platform.runLater(() -> {
                        Map<String, String> params = new HashMap<>();
                        params.put("fileId", String.valueOf(item.getId()));
                        Boolean deleteResult = RequestComponent.get("/operation_file/delete_by_file", Boolean.class, params);
                        if (deleteResult) {
                            fileObservableList.remove(item);
                        }
                    }));


                    RingProgressIndicator progressIndicator = new RingProgressIndicator(0, false);
                    progressIndicator.setMinSize(40, 40);
                    DownLoadFileService downLoadFileService = new DownLoadFileService(0L, item.getFileSize(), item.getId(), item.getFileName());
                    //创建进度监听
                    ChangeListener<Number> progressBind = (observable, oldValue, newValue) ->
                            progressIndicator.setProgress(downLoadFileService.getProgress());
                    // 在事件处理中确保在JavaFX Application Thread上执行
                    download.setOnMouseClicked(event -> Platform.runLater(() -> {
                        if (isStart) {
                            downLoadFileService.cancel();
                            downLoadFileService.reset();
                            isStart = Boolean.FALSE;
                            //当取消的时候需要解绑监听，防止值被错误的赋予
                            downLoadFileService.progressProperty().removeListener(progressBind);
                            progressIndicator.setProgress((double) downLoadFileService.getCurrentSize() / (double) item.getFileSize());
                            download.setGraphic(new FontIcon(AntDesignIconsOutlined.DOWNLOAD));
                            return;
                        }
                        downLoadFileService.start();
                        isStart = Boolean.TRUE;
                        download.setGraphic(new FontIcon(AntDesignIconsOutlined.STOP));
                        //把下载进度和进度展示进行绑定
                        downLoadFileService.progressProperty().addListener(progressBind);
                    }));

                    downLoadFileService.stateProperty().addListener((observable, oldValue, newValue) -> {
                        if (newValue == Worker.State.SUCCEEDED) {
                            // 任务完成时执行相应的操作
                            download.setGraphic(new FontIcon(AntDesignIconsOutlined.CHECK));
//                            DownloadFileRecord fileRecord = new DownloadFileRecord();
//                            fileRecord.setFileName(item.getFileName());
//                            fileRecord.setFileLocalUrl("");
//                            fileRecord.setFileMd5(item.getFileMd5());
//                            fileRecord.setDownloadProgress(100);
//                            fileRecord.setFileNetUrl("");
//                            fileRecord.setFileLocalUrl("");
//                            fileRecord.setCreateTime(LocalDate.now().toString());
//                            fileRecord.setUpdateTime(LocalDate.now().toString());
//
//                            //插入下载记录
//                            DownloadFileService fileService = new DownloadFileServiceImpl();
//                            int i = fileService.insertRecord(fileRecord);
//                            System.out.println("插入记录：" + i);
                        }
                    });


                    HBox box = new HBox(20, progressIndicator, download, delete);
                    box.setAlignment(Pos.CENTER_RIGHT);
                    box.setPadding(new Insets(0, 50, 0, 0));

                    this.setOnMouseEntered(event -> this.setStyle(StyleConstant.LIST_VIEW_STYLE_EXITED));
                    hBox.getChildren().addAll(view, tile);
                    borderPane.setLeft(hBox);
                    borderPane.setRight(box);
                    borderPane.prefWidthProperty().bind(width);

                    VBox vBox = new VBox();
                    //使用main的css
                    vBox.getStylesheets().add("css/controller/main-controller.css");
                    vBox.getStyleClass().add("list-view-download-vbox");
                    vBox.getChildren().add(borderPane);

                    this.setGraphic(vBox);
                    //设置移入变色
                    this.setOnMouseEntered(event -> this.setStyle(StyleConstant.LIST_VIEW_STYLE_ENTER));
                    this.setOnMouseExited(event -> this.setStyle(StyleConstant.LIST_VIEW_STYLE_EXITED));
                }
            }
        };
    }

    /**
     * 实例化
     *
     * @return View
     */
    public static FileListView newInstance(DoubleBinding width, ObservableList<FileListModel> fileObservableList) {
        return new FileListView(width, fileObservableList);
    }
}
